package com.dmall.algorithm.chapter01;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Leetcode15 {
    public List<List<Integer>> threeSum(int[] nums) {// 总时间复杂度：O(n^2)
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length <= 2) {
            return res;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            if (nums[i] > 0) break;
            if (i > 0 && nums[i] == nums[i - 1]) continue; // 去掉重复情况
            int left = i + 1, right = nums.length - 1;
            int target = - nums[i];
            while (left < right) {
                if (nums[left] + nums[right] == target) {
                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    left ++;
                    right --;
                    while (left < right && nums[left] == nums[left - 1]) left ++;
                    while (left < right && nums[right] == nums[right + 1]) right --; // 这里需要注意，是right + 1，因为right已经加了1了
                } else if (nums[left] + nums[right] < target) {
                    left ++;
                } else {
                    right --;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4};
        Leetcode15 leetcode15 = new Leetcode15();
        System.out.println(leetcode15.threeSum(nums));
    }
}
